//
//  HWComposeViewConreoller.m
//  01-黑马微博
//
//  Created by lanou3g on 15/9/17.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import "HWComposeViewConreoller.h"
#import "HWAccountTool.h"
#import "HWTextView.h"
#import "AFNetworking.h"
#import "HWAccount.h"
#import "MBProgressHUD+MJ.h"
#import "HWComposeToolbar.h"
#import "HWComposePhotoView.h"
@interface HWComposeViewConreoller ()<UITextViewDelegate, HWComposeToolbarDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property(nonatomic, weak) UITextView *textView;
@property (nonatomic, weak) HWComposeToolbar *toolbar;
/**相册（存放拍照或者相册中选择的照片）*/
@property (nonatomic, weak) HWComposePhotoView *photoView;;
@end
@implementation HWComposeViewConreoller
- (void)viewDidLoad{
    [super viewDidLoad];
    //设置导航栏
    [self setupNav];
    //设置textView
    [self setupTextView];
    /**设置工具条*/
    [self setupToolbar];
    /**添加相册*/
    [self setupPhotsView];
}
- (void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    UILabel *titleLabel = [[UILabel alloc] init];
    //自动换行
    NSString *name = [HWAccountTool account].name;
    if (name) {
        titleLabel.numberOfLines = 0;
        titleLabel.width = 200;
        titleLabel.height = 44;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        
        NSString *str = [NSString stringWithFormat:@"发微博\n%@",name];
        //创建一个带有属性的字符串（比如颜色属性）
        NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:str];
        //添加属性
        [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:[str rangeOfString:name]];
        
        titleLabel.attributedText = attriStr;
    }else{
    self.title = @"发微博";
    }
    self.navigationItem.titleView = titleLabel;

}
/**
 *  设置textView
 */
- (void)setupTextView{
    HWTextView *textView = [[HWTextView alloc] init];
    textView.placeholdr = @"分享新鲜事...";
    textView.placeholdrColor = [UIColor grayColor];
    textView.frame = self.view.bounds;
    textView.font = [UIFont systemFontOfSize:17];
    textView.delegate = self;
    textView.alwaysBounceVertical = YES;
    [textView becomeFirstResponder];
    [self.view addSubview:textView];
    self.textView = textView;
    //文字改变
    [HWNotificationCenter addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:textView];
//    键盘通知
   [HWNotificationCenter addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
/**
 *  设置工具条
 */
- (void)setupToolbar{
    HWComposeToolbar *toolbar = [[HWComposeToolbar alloc] init];
    toolbar.delegate = self;
    toolbar.width = self.view.width;
    toolbar.height = 44;
    toolbar.y = self.view.height - toolbar.height;
    [self.view addSubview:toolbar];
    self.toolbar = toolbar;
}
/**
 *  设置相册
 */
- (void)setupPhotsView{
    HWComposePhotoView *photoView = [[HWComposePhotoView alloc] init];
    photoView.width = self.view.width;
    [self.textView addSubview:photoView];
    self.photoView = photoView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.rightBarButtonItem.enabled = NO;

}
- (void)cancel{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 发微博
- (void)send{
//https://api.weibo.com/2/statuses/update.json
//    status 	true 	string 	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
//    access_token 	false 	string
    HWAccount *account = [HWAccountTool account];

    //   1. 请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //  2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"status"] = self.textView.text;
    //  3.发送请求
    [mgr POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        [MBProgressHUD showSuccess:@"发送成功"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD showError:@"发布失败"];

    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 实现composeToolbarDelegate
- (void)composeToolbar:(HWComposeToolbar *)toolbar didClickedButton:(HWComposeToolbarType)index{
    switch (index) {
        case HWComposeToolbarCamera:
            [self openCamera];
            break;
        case HWComposeToolbarPicture:
            [self openAlbum];

            break;
        case HWComposeToolbarMention:
                       break;
        case HWComposeToolbarTrend:
            

            break;
        case HWComposeToolbarEmotion:
    

            break;
    }
}
#pragma mark - 拍照方法
- (void)openCamera{
    [self getImageWithType:UIImagePickerControllerSourceTypeCamera];
}

- (void)openAlbum{
    [self getImageWithType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (void)getImageWithType:(UIImagePickerControllerSourceType)type{
    if ([UIImagePickerController isSourceTypeAvailable:type]) {
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = type;
        ipc.delegate = self;
        [self presentViewController:ipc animated:YES completion:nil];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
   UIImage *image = info[UIImagePickerControllerOriginalImage];
    //添加图片到photoView中
    HWLog(@"%@", info);
    [self.photoView addPhoto:image];
}
#pragma mark - 监听键盘frame
- (void)keyboardWillChangeFrame:(NSNotification *)sender{
    NSDictionary *userInfo = sender.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 执行动画
    [UIView animateWithDuration:duration animations:^{
        // 工具条的Y值 == 键盘的Y值 - 工具条的高度
        if (keyboardF.origin.y > self.view.height) { // 键盘的Y值已经远远超过了控制器view的高度
            self.toolbar.y = self.view.height - self.toolbar.height;
        } else {
            self.toolbar.y = keyboardF.origin.y - self.toolbar.height;
        }
        HWLog(@"%@", NSStringFromCGRect(self.toolbar.frame));
    }];
    /*
     UIKeyboardFrameBeginUserInfoKey = NSRect: {{0, 352}, {320, 216}};
     UIKeyboardCenterEndUserInfoKey = NSPoint: {160, 442};
     UIKeyboardBoundsUserInfoKey = NSRect: {{0, 0}, {320, 252}};
     UIKeyboardFrameEndUserInfoKey = NSRect: {{0, 316}, {320, 252}};
     UIKeyboardAnimationDurationUserInfoKey = 0.25;
     UIKeyboardCenterBeginUserInfoKey = NSPoint: {160, 460};
     UIKeyboardAnimationCurveUserInfoKey = 7;
     */
}
#pragma mark - uitextView代理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)textChange{
    self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText;
}
- (void)dealloc{
    [HWNotificationCenter removeObserver:self];
}
@end
